import React from 'react';
import { connect } from 'react-redux';
import moment from 'moment';
import { DATE_FORMMATTER } from '../../../constants/datetime';

import { Level2Navigator,
		 Paper,
		 PaperTitle,
		 PaperContent,
		 PaperFooter,
		 ChartsActive,
		 ChartsRise,
		 BasicTable,
		 SwitchDate,
		 Information } from '../components/dumb';
import { switchView,
		/*获取图表数据，post请求方式，有固定参数*/
	 	 getBasicTable,
	 	 getActiveTable,
	 	 getChartsBasic,
	 	 getChartsActive,
	 	 getBasicDetail,
	 	 selectBasicDetailPageIndex,
	 	 selectBasicDetailCurrentPageIndex,
	 	 getActiveDetail,
	 	 selectActiveDetailPageIndex,
	 	 selectActiveDetailCurrentPageIndex,
	 	 reset as basicReset
	 	} from '../actions/basicOverview';
import { ListPagesTurnButton } from '../components/smart';
import { 
		 setDateRange,
	 	 	} from '../actions/filter';	
import { switchSubView } from '../actions/level3Navigator';

import Filter from './Filter';
  
import { BASIC, CHART } from '../../../constants/basicOverview';
import { CITY, COUNTY, SCHOOL } from '../../../constants/area';
import cx from 'classnames';

import * as BasicOverviewStyle from './BasicOverview.less';

function mapStateToProps(state) {
	let { basicOverview, filter, level3Navigator } = state;
	return {
		basicOverview,
		filter,
		level3Navigator
	};
}

function getAdressLable(city, county, school) {
	let arr = [city.selectedItem, county.selectedItem, school.selectedItem];
	return arr.map((item) => {
		if (item)
			return item.name;
		else
			return '';
	}).join('')
}
/**
 * [getAera 获取当前区域的最下级地域]
 * @param  {[type]} props [状态属性]
 * @return {[type]}       [description]
 */
function getAera(props) {
	let { filter }=props;

	if (filter.school.selectedItem.name){
		return 'school'
	} else if (filter.county.selectedItem.name){
		return 'county'
	} else {
		return 'city'
	}
};
function getPageIndex(arr) {
	return Math.ceil(arr.length/20);
};
function getPageList(arr, pageIndex){
	return arr.slice((pageIndex-1)*20, pageIndex*20);
};
/**
 * 过滤掉基础概览中直辖市上级地域不存在产生的无效数据
 */
function deleteError(arr){
	if (arr[1] && !arr[1][0])arr.pop();
	return arr;
}
/**
 * [根据筛选器刷新页面]
 * @param  {[type]} props [获取props]
 * @param  {[type]} area  [获取当前地域信息]
 * @return {[type]}       [description]
 */
function getData( props, area, desc, orderBy){
	let { dispatch, filter, basicOverview } = props;
	let { view } = basicOverview;
	let cityDetailParams,countyDetailParams;

	/**
	 * 获取基础表格数据
	 * @type {[type]}
	 */
	let { city, county, school, dateRange, subject, grade } =filter;
	/**
	 * [filterSelectedItems 提取筛选项共用部分]
	 * @type {Object}
	 */
	let filterSelectedItems = {
		startDate: dateRange[0],
		endDate: dateRange[1],
		subjects: subject.selectedItems,
		grades: grade.selectedItems
	};

	let cityParams = {
		cityId: city.selectedItem.enum,
		provinceName: city.selectedItem.parentName,
		cityName: city.selectedItem.name,
		provinceId: city.selectedItem.parentId,
	};
	Object.assign(cityParams,filterSelectedItems);
	
	let countyParams = {
		countyId: county.selectedItem.enum,
		cityName: city.selectedItem.name || county.selectedItem.parentName,
		countyName: county.selectedItem.name,
		cityId: city.selectedItem.enum || county.selectedItem.parentId
	};
	Object.assign(countyParams,filterSelectedItems);

	let schoolParams = {
		schoolId: school.selectedItem.enum,
		countyName:  county.selectedItem.name ||school.selectedItem.parentName,
		schoolName: school.selectedItem.name,
		countyId: county.selectedItem.enum || school.selectedItem.parentId
	};
	Object.assign(schoolParams,filterSelectedItems);
	if (orderBy) {
		cityDetailParams = Object.assign({},cityParams,{
			desc:desc,
			orderBy,
			startDate:'1970-01-01'
		});
		countyDetailParams = Object.assign({},countyParams,{
			desc:desc,
			orderBy,
			startDate:'1970-01-01'
		})
	}
	let cityParamsCount = Object.assign({},cityParams,{
		startDate:'1970-01-01'
	})
	let countyParamsCount = Object.assign({},countyParams,{
		startDate:'1970-01-01'
	})
	let schoolParamsCount = Object.assign({},schoolParams,{
		startDate:'1970-01-01'
	})
	/**
	 * [switch 根据不同地域请求不同数据]
	 * @param  {[type]} area [地域类型]
	 * @return {[type]}      [description]
	 */
	switch (area) {
		case 'city':
			/**
			 * [if 当目前为活跃热力图时不请求基础视图相关数据]
			 * @param  {[type]} view [当前视图]
			 * @return {[type]}      [description]
			 */
			if (view == CHART){
				dispatch(getActiveTable('city', cityParams));
				dispatch(getChartsActive('city', cityParams));
				
				if (orderBy) {
					dispatch(getActiveDetail('city', cityDetailParams));		
				} else {
					dispatch(getActiveDetail('city', cityParams));
				}
				return;
			}
			/**
			 * 请求基础视图数据
			 */
			if (orderBy){
				dispatch(getBasicDetail('city', cityDetailParams));	
			}else {
				dispatch(getBasicTable('city', cityParamsCount));
				dispatch(getChartsBasic('city', cityParams));
				dispatch(getBasicDetail('city', cityParamsCount));
			}		
			break;
		case 'county':
			if (view == CHART){
				dispatch(getActiveTable('county', countyParams))
				
				if (orderBy) {
					dispatch(getActiveDetail('county', countyDetailParams));		
				} else {
					dispatch(getActiveDetail('county', countyParams))

				}
				return
			}
			if (orderBy){
				dispatch(getBasicDetail('county', countyDetailParams));
			}else{
				dispatch(getBasicDetail('county', countyParamsCount));
				dispatch(getBasicTable('county', countyParamsCount));
				dispatch(getChartsBasic('county', countyParams))
			}
			break;
		case 'school':
			if (view == CHART){
				dispatch(getActiveTable('school', schoolParams))
				return
			}
			dispatch(getBasicTable('school', schoolParamsCount))
			dispatch(getChartsBasic('school', schoolParams))
			break;
		default:

	}
}

class BasicOverview extends React.Component {

	constructor(props) {
		super(props);
	}

	lv2Items = [{
			ID: BASIC,
			label: '基础概况'
		}, {
			ID: CHART,
			label: '活跃热力图'
		}];

	/**
	 * 获取当前筛选条件下图表数据
	 * @return {[type]} [description]
	 */
	getCurrentData = (desc,orderBy) => {
		// 定时器设置延迟，目的是获取最新store
		let timer = setTimeout(() => {
			let props = this.props;
			let area = getAera(props);
			getData(props, area, desc,orderBy)
			clearTimeout(timer)
		}, 0)
	};

	componentWillMount(){
		this.getCurrentData();
	};

	/*切换二级视图（活跃热力图，基础概况）*/
	handleSwitchView = (view) => {
		let { dispatch } = this.props;
		dispatch(switchView(view));
		this.resetDateRange()
		this.getCurrentData()
	};

	/**
	 * [componentWillReceiveProps 状态改变时写入数据详情页码]
	 * @param  {[type]} nextProps [description]
	 * @return {[type]}           [description]
	 */
	componentWillReceiveProps (nextProps) {
		let { dispatch, basicOverview } = nextProps;
		let { detail, view } = basicOverview;
		let { active, basic } = detail;
		let pageIndex = getPageIndex(basic.dataSource);
		let oldPageIndex = 1;
		if ( view == CHART ) {
			pageIndex = getPageIndex(active.dataSource);
			
			oldPageIndex = this.props.basicOverview.detail.active.pageIndex;
			if ( pageIndex ==  oldPageIndex )return;
			dispatch(selectActiveDetailPageIndex(pageIndex));
			dispatch(selectActiveDetailCurrentPageIndex(1));
		} else {
			pageIndex = getPageIndex(basic.dataSource);

			oldPageIndex = this.props.basicOverview.detail.basic.pageIndex;
			if ( pageIndex ==  oldPageIndex )return;

			dispatch(selectBasicDetailPageIndex(pageIndex));
			dispatch(selectBasicDetailCurrentPageIndex(1));
		};
	}
	/**
	 * 筛选器变化事件
	 */
	handleFilterChange = () => {
		this.getCurrentData();
	};
	//数据详情排序flag
  	state = {
    	descStu:true,
    	descTec:true,
    	descSch:true,
    	descTotal: true,
    	descOnlineStudent: true,
    	descOnlineTeacher: true,
    	descSubmits: true,
    	descFixpus: true
    };
    /*数据详情排序*/
    handleDetailSort = (item) => {
		let { descStu, descTec, descSch, descTotal, descOnlineStudent, descOnlineTeacher, descSubmits, descFixpus} = this.state;
    	switch(item){
    		case '累计学生' :
    		{	
    			this.setState({
    			    descStu:!descStu,
    			    descTec:true,
    			    descSch:true	
    			})
  
    			this.getCurrentData(this.state.descStu,'student')
    			break;
    		}
    		
    		case '累计教师' :
			{	
				this.setState({
    			    descTec:!descTec,
    			    descStu:true,
    			    descSch:true		
    			});
				this.getCurrentData(this.state.descTec,'teacher')
	    		break;
    		}
    		case '累计学校' :
    		{
    			this.setState({
    			    descSch:!descSch,
    			    descStu:true,
    			    descTec:true		
    			})
    			this.getCurrentData(this.state.descSch,'school')
    		    break;
    		}
    		case '在线总人数':
    		{
    			this.setState({
    			    descTotal: !descTotal,
			    	descOnlineStudent: true,
			    	descOnlineTeacher: true,
			    	descSubmits: true,
			    	descFixpus: true	
    			})
    			this.getCurrentData(this.state.descTotal,'total')
    		    break;
    		}
    		case '在线学生':
    		{
    			this.setState({
    			    descTotal: true,
			    	descOnlineStudent: !descOnlineStudent,
			    	descOnlineTeacher: true,
			    	descSubmits: true,
			    	descFixpus: true	
    			})
    			this.getCurrentData(this.state.descOnlineStudent,'onlineStudent')
    		    break;
    		}
    		case '在线教师':
    		{
    			this.setState({
    			    descTotal: true,
			    	descOnlineStudent: true,
			    	descOnlineTeacher: !descOnlineTeacher,
			    	descSubmits: true,
			    	descFixpus: true	
    			})
    			this.getCurrentData(this.state.descOnlineTeacher,'onlineTeacher')
    		    break;
    		}
    		case '提交作业学生':
    		{
    			this.setState({
    			    descTotal: true,
			    	descOnlineStudent: true,
			    	descOnlineTeacher: true,
			    	descSubmits: !descSubmits,
			    	descFixpus: true	
    			})
    			this.getCurrentData(this.state.descSubmits,'submits')
    		    break;
    		}
    		case '布置作业教师':
    		{
    			this.setState({
    			    descTotal: true,
			    	descOnlineStudent: true,
			    	descOnlineTeacher: true,
			    	descSubmits: true,
			    	descFixpus: !descFixpus
    			})
    			this.getCurrentData(this.state.descFixpus,'fixpus')
    		    break;
    		}
    		default:
    	}
    };
    /**
	 * 数据详情翻页
	 * @return {[type]} [description]
	 */
	handleSwitchPageList = (pageIndex) => {
		let { dispatch, basicOverview } = this.props;
		let { view } = basicOverview;
		if ( view == BASIC ) {
			dispatch(selectBasicDetailCurrentPageIndex(pageIndex)) 
		} else {
			dispatch(selectActiveDetailCurrentPageIndex(pageIndex)) 
		};
	};

    resetDateRange = () => {
    	let { dispatch } = this.props;
		let now = moment().subtract(1, 'days');
		let lastMonth=moment().subtract(1, 'M');
		dispatch(setDateRange([lastMonth.format(DATE_FORMMATTER), now.format(DATE_FORMMATTER)]));
    };
   
	componentDidMount() {
		let { dispatch } = this.props;
		this.resetDateRange()
		dispatch(basicReset())
	};
	render() {
		let basicTableHeader = {
				textArray:['地域','累计学生','累计教师','累计学校'],
				isDesc:[false,false,false,false]
			},
			basicTableDetailHeader = {
				textArray:['地域','累计学生','累计教师','累计学校'],
				isDesc:[false,true,true,true]
			};
		let basicTableHeaderNoSchool = {
				textArray:['地域','累计学生','累计教师'],
				isDesc:[false,false,false]
			},
			basicTableDetailHeaderNoSchool = {
				textArray:['地域','累计学生','累计教师'],
				isDesc:[false,true,true]
			};
		let activeTableHeader = {
				textArray:['地域','在线学生','在线教师','提交作业学生','布置作业教师'],
				isDesc:[false,false,false,false,false]
			},
			activeTableDetailHeader = {
				textArray:['地域','在线总人数','在线学生','在线教师','提交作业学生','布置作业教师'],
				isDesc:[false,true,true,true,true,true]
			};
		
		let { basicOverview, filter, level3Navigator } = this.props;
		let { view, charts, detail, basicTable, activeTable, message} = basicOverview;
		let { subView } = level3Navigator;

		let { subject, grade, dateRange, city, county, school } = filter;
		let { descSch, descStu, descTec, descTotal, descOnlineStudent, descOnlineTeacher, descSubmits, descFixpus } = this.state;

		/*获取各级地域名*/
		let address = getAdressLable(city,county,school);
		/*登录状态相关数据*/
		let { authentication } = this.props;
		
		return (
			<div className={BasicOverviewStyle.basicOverview}>
				<Information label={message} isOpen={!!message} />
				<Level2Navigator items={this.lv2Items} selectedItem={view} 
					onChange={this.handleSwitchView} />
				<Filter hasDateSelector={view==BASIC} hasSwitchDate={view==CHART} subView={subView} onFilterChange={this.handleFilterChange} />
				{ view == BASIC && 
				<Paper>
					<PaperTitle>
						<div className='titleBar overview'>
							<span><b>{address}数字化教育概况</b></span>
						</div>
					</PaperTitle>
					<PaperContent >
						<BasicTable data={deleteError(basicTable.dataSource)} tableHeader={basicTableHeader} isBackgroundColor={false} />
					</PaperContent>
				</Paper>
				}
				{ view == BASIC && 
				<Paper>
					<PaperTitle>
						<div className='titleBar'>
							<span><b>{address}新增趋势</b></span>
						</div>
					</PaperTitle>
					<PaperContent >
						<ChartsRise chartsBasic={charts.basic} city={city} county={county} school={school} currentSubView={subView} currentView={view}/>	
					</PaperContent>
					<PaperFooter>
						[ 注: 新增学生和学校数无学科区分 ]
					</PaperFooter>
				</Paper>
				}
				{ view == BASIC && subView != SCHOOL && 
				<Paper>
					<PaperTitle>
						<div className='titleBar'>
							<span><b>数据详情</b></span>
						</div>
					</PaperTitle>
					<PaperContent>
						{subView==CITY&&
							<BasicTable data={detail.basic.dataSource} tableHeader={basicTableDetailHeader} isBackgroundColor={true} onDetailSort={this.handleDetailSort}
												orderFlag = {[false, descStu, descTec, descSch]}/>
						}
						{subView==COUNTY&&
							<BasicTable data={getPageList(detail.basic.dataSource, detail.basic.currentPageIndex)} tableHeader={basicTableDetailHeaderNoSchool} isBackgroundColor={true} onDetailSort={this.handleDetailSort}
												orderFlag = {[false, descStu, descTec, descSch]}/>
						}
					</PaperContent>
					<PaperFooter>
							<ListPagesTurnButton pageIndex={detail.basic.pageIndex} onPaging={this.handleSwitchPageList} currentPageIndex={detail.basic.currentPageIndex}/>
					</PaperFooter>
				</Paper>
				}
				{ view == CHART &&
				<Paper>
					<PaperTitle>
						<div className='titleBar overview'>
							<span><b>{address}师生活跃概况</b></span>
							
						</div>
					</PaperTitle>
					<PaperContent>
						<BasicTable data={deleteError(activeTable.dataSource)} tableHeader={activeTableHeader} isBackgroundColor={false}/>
					</PaperContent>
				</Paper>
				}
				{ view == CHART && subView == CITY &&
				<Paper>
					<PaperTitle>
						<div className='titleBar trend'>
							<span><b>{address}活跃热力图</b></span>
						</div>
					</PaperTitle>
					<PaperContent height={715} >
						<ChartsActive data={charts.active.geo} areaName={city.selectedItem.name}/>
					</PaperContent>
				</Paper>
				}
				{ view == CHART && subView != SCHOOL &&
				<Paper>
					<PaperTitle>
						<div className='titleBar'>
						<span><b>数据详情</b></span>
						</div>
					</PaperTitle>
					<PaperContent>
						<BasicTable data={getPageList(detail.active.dataSource, detail.active.currentPageIndex)} tableHeader={activeTableDetailHeader} isBackgroundColor={true}  onDetailSort={this.handleDetailSort}
									orderFlag = {[false, descTotal, descOnlineStudent, descOnlineTeacher, descSubmits, descFixpus]}/>
					</PaperContent>
					<PaperFooter>
						<ListPagesTurnButton pageIndex={detail.active.pageIndex} onPaging={this.handleSwitchPageList} currentPageIndex={detail.active.currentPageIndex}/>
					</PaperFooter>
					<PaperFooter>
						[ 注: 在线总人数为在线学生, 在线教师之和 ]
					</PaperFooter>
				</Paper>
				}
			</div>
			);
	}
}

export default connect((state)=>state)(BasicOverview)
